package com.socialin.android.hackaton.fragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.socialin.android.hackaton.draw.R;
import com.socialin.android.hackaton.draw.adapter.ChatListAdapter;
import com.socialin.android.hackaton.draw.listener.JsonReceiver;
import com.socialin.android.hackaton.draw.listener.JsonSender;

public class ChatFragment extends Fragment implements JsonReceiver{
	
	private JsonSender jsonSender = null;
	
	private EditText myChatTextEditText = null;
	private ListView chatListView = null;
	private ChatListAdapter chatAdapter = null;
	private static String userName = Build.MODEL;
	
	private SlidingDrawer chatSlidingDrawer = null;
	
	private Button slidingDrawerButton = null;
	
	private Toast bubbleToast = null;
	
	private SoundPool tada = null;
	
	private int unReadedComments = 0;
	
	private boolean isSoundLoaded = false;
	private int soundId = 0; 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	public void setSlidingDrawer(SlidingDrawer drawer){
		this.chatSlidingDrawer = drawer;
		slidingDrawerButton = (Button)chatSlidingDrawer.findViewById(R.id.handle);
		chatSlidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			
			@Override
			public void onDrawerOpened() {
				unReadedComments = 0;
				if(slidingDrawerButton == null)
					slidingDrawerButton = (Button)chatSlidingDrawer.findViewById(R.id.handle);
				slidingDrawerButton.setText("");
				chatListView.setSelection(Math.max(chatListView.getAdapter().getCount()-1,0));
			}
		});
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View chatFragmentLayout = getActivity().getLayoutInflater().inflate(R.layout.chat_fragment_layout, null);
		

		myChatTextEditText = (EditText) chatFragmentLayout.findViewById(R.id.chat_text_edittext);
		
		myChatTextEditText.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId == EditorInfo.IME_ACTION_DONE){
					sendChatMessage(myChatTextEditText.getText().toString());
				}
				return false;
			}
		});
		chatListView = (ListView)chatFragmentLayout.findViewById(R.id.chat_listview_id);
		
		chatAdapter = new ChatListAdapter(getActivity(), 0);
		chatListView.setAdapter(chatAdapter);
		
		chatFragmentLayout.findViewById(R.id.chat_send_button).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sendChatMessage(myChatTextEditText.getText().toString());
				
			}
		});
		
		
		return chatFragmentLayout; 
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		tada = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
		soundId = tada.load(activity, R.raw.sound, 1);
		tada.setOnLoadCompleteListener(new OnLoadCompleteListener() {
			
			@Override
			public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
				// TODO Auto-generated method stub
				isSoundLoaded = true;
			}
		});
		
	}
	
	
	private void sendChatMessage(String msg){
		if(msg.trim().equals("")){
			return;
		}
		if(jsonSender == null){
			throw new IllegalStateException();
		}
		
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("action", "message");
			jsonObject.put("user_name", userName);
			JSONArray paramsArray = new JSONArray();
			JSONObject paramsObject = new JSONObject();
			paramsObject.put("message", msg);
			paramsArray.put(paramsObject);
			jsonObject.put("params", paramsArray);
			jsonSender.onSend(jsonObject);
//			chatAdapter.add(jsonObject);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		myChatTextEditText.setText("");
		
	}
	
	public void setJSONSender(JsonSender sender){
		this.jsonSender = sender;
	}
	
	public JsonSender getJSONSender(){
		return jsonSender;
	}
	
	@Override
	public void onDetach() {
		super.onDetach();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onReceive(JSONObject json) {
		chatAdapter.add(json);
		if (chatSlidingDrawer != null && chatSlidingDrawer.isOpened()) {
			chatListView.setSelection(Math.max(chatListView.getAdapter()
					.getCount() - 1, 0));
		} else {
			try {
				if(isSoundLoaded){
					tada.play(soundId, 1.f, 1.f, 1, 0, 1.f);
				}
				unReadedComments++;
				if (slidingDrawerButton != null) {
					slidingDrawerButton.setText("" + unReadedComments);
				}
				bubbleToast = Toast.makeText(
						getActivity(),
						json.getJSONArray("params").getJSONObject(0)
								.optString("message"), Toast.LENGTH_SHORT);
				bubbleToast.setGravity(Gravity.TOP | Gravity.RIGHT, 10, 10);
				bubbleToast.show();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
